//
//  LiveStreamRoomViewModel.swift
//  live
//
//  Created by melvyn on 2018/8/17.
//  Copyright © 2018 NEET. All rights reserved.
//

import Foundation
import RxSwift
import RxCocoa
import Link

final class LiveStreamRoomViewModel: RxViewModel {
    
    let disposeBag = DisposeBag()
    
    var title:BehaviorRelay<String?>
    
    var ijkplayer: IJKFFMoviePlayerController
    
    var liveStream: LiveStream!
    
    let avatar: Observable<Thumbnail>
    let nickname: Driver<String?>
    let level: Driver<String>
    let compose: PublishSubject<Void> = PublishSubject()
    let comment: BehaviorRelay<String?> = BehaviorRelay(value: nil)
    let danmakuListViewModel: DanmakuListViewModel
    let messenger: Messenger
    
    init(_ liveStream: LiveStream) {
        self.liveStream = liveStream
        messenger = Messenger.init(liveStream.id)
        messenger.open()
        
        avatar = Observable.just(liveStream)
            .map({ ($0.upload?.avatar,  "default_avatar_64x64_") })
        
        nickname = Observable.just(liveStream)
            .map { $0.upload?.nickname }
            .asDriver(onErrorJustReturn: "--")
        
        level = Observable.just(liveStream)
            .map { $0.upload?.level != nil ? "UP\($0.upload!.level!)" : "--"}
            .asDriver(onErrorJustReturn: "--")
        
        title = BehaviorRelay(value: liveStream.title)
        
        ijkplayer = IJKFFMoviePlayerController.init(url: APIClient.Route.RTMP.description + liveStream.key!, options: .default)
        
        let danmakus = messenger.comments()
            .map { $0.value }
            .unwrap()
        
        danmakuListViewModel = DanmakuListViewModel.init(danmakus: danmakus)
        
        compose.withLatestFrom(messenger.isConnected)
            .debug()
            .filter({ $0 })
            .withLatestFrom(comment)
            .unwrap()
            .map({ Comment.MultipartForm.init(liveID: liveStream.id, content: $0) })
            .flatMapLatest {[unowned self] in self.messenger.compose($0) }
            .subscribe()
            .disposed(by: disposeBag)
        
        ijksetup(ijkplayer)
    }
    
    private func ijksetup(_ ijkplayer: IJKFFMoviePlayerController) {
        ijkplayer.shouldAutoplay = true
        ijkplayer.scalingMode = .aspectFit
        
        IJKFFMoviePlayerController.setLogReport(false)
    }
}
